import "./style/index.scss";
import { Button } from "antd";
import { Input, Upload, Image } from "antd";
import { FolderOpenOutlined, FrownOutlined } from "@ant-design/icons";
import { useEffect, useState, useRef } from "react";
import { getDate, downFile } from "@/utils/tools";
import { uploadFile } from "@/api/downLoad";
import { emoji } from "@/utils/emoji";

const ChatRoom = () => {
  const userInfo = JSON.parse(localStorage.getItem("userInfo"));
  let timer = null;
  const [text, setText] = useState("");
  const [showEmoji, setShowEmoji] = useState(false);
  let textCopy = useRef("");
  const [msgList, setMsgList] = useState([]);
  let ws = useRef(null);
  const msglistRef = useRef(null);
  const { TextArea } = Input;
  useEffect(() => {
    initWs();
    window.addEventListener("keydown", (e) => {
      if (e.keyCode === 13) {
        e.preventDefault();
        if (ws.current && textCopy.current !== "") {
          sendMsg(textCopy.current);
        }
      }
    });
  }, []);
  useEffect(() => {
    msglistRef.current.scrollTop = 9999999;
  }, [msgList]);
  useEffect(() => {
    textCopy.current = text;
  }, [text]);
  const handleUpload = (file) => {
    // 发起上传请求，返回 Promise 对象
    const formData = new FormData();
    formData.append("file", file.file);
    uploadFile(formData).then((res) => {
      if (res.code === 200) {
        ws.current.send(
          JSON.stringify({
            type: file.file.type,
            from: {
              name: userInfo.userName,
              id: userInfo.uid,
              time: getDate(new Date()),
            },
            url: res.path,
            fileName: res.name,
          })
        );
      }
    });
  };
  const sendMsg = (msg) => {
    // 群聊消息
    ws.current.send(
      JSON.stringify({
        type: "message",
        from: {
          name: userInfo.userName,
          id: userInfo.uid,
          time: getDate(new Date()),
        },
        msg: msg || text,
      })
    );

    // 私聊消息
    // ws.current.send(
    //   JSON.stringify({
    //     type: "message",
    //     from: {
    //       name: userInfo.userName,
    //       id: userInfo.uid,
    //       time: getDate(new Date()),
    //     },
    //     to: {
    //       name: "cy",
    //       id: "96cdab30b8d511eebdd55b35418c1809",
    //     },
    //     msg: msg || text,
    //   })
    // );
    setText("");
  };
  const parseMsgContent = (msg) => {
    if (msg.type === "message") {
      return (
        <div>
          {msg.from.name}：{msg.msg}
        </div>
      );
    } else if (msg.type === "image/png") {
      return (
        <div>
          {msg.from.name}：<Image src={msg.url} />
        </div>
      );
    } else {
      return (
        <div className="file">
          <div>{msg.fileName}</div>
          <div onClick={() => downFile(msg.fileName)}>下载文件</div>
        </div>
      );
    }
  };
  const initWs = () => {
    ws.current = new WebSocket("ws://47.108.128.216:5000/chat");
    ws.current.onopen = () => {
      console.log("连接成功");
      ws.current.send(
        JSON.stringify({
          type: "login",
          id: userInfo.uid,
        })
      );
      timer = setInterval(() => {
        ws.current.send(
          JSON.stringify({
            type: "heartbeat",
            msg: "ping",
          })
        );
      }, 10000);
    };
    ws.current.onmessage = (event) => {
      console.log(JSON.parse(event.data));
      setMsgList((prev) => [...prev, JSON.parse(event.data)]);
    };
    ws.current.onclose = () => {
      console.log("连接关闭");
      clearInterval(timer);
      initWs();
    };
    ws.current.onerror = (event) => {
      console.log("连接出错");
    };
  };
  return (
    <div className="main">
      <div className="chatRoom">
        <div>
          <div>聊天室</div>
          <div className="userList" ref={msglistRef}>
            {msgList.map((msg, index) => {
              return (
                <div
                  className={
                    msg.from.id === userInfo.uid ? "userRight" : "user"
                  }
                  key={index}
                >
                  <div>{msg.from.time}</div>
                  {parseMsgContent(msg)}
                </div>
              );
            })}
          </div>
        </div>
        <div>
          <div className="function">
            <div>
              <Upload showUploadList={false} customRequest={handleUpload}>
                <FolderOpenOutlined style={{ fontSize: "16.5pt" }} />
              </Upload>
            </div>
            <div>
              <FrownOutlined onClick={() => setShowEmoji(!showEmoji)} />
              {showEmoji && (
                <div className="emoji">
                  {emoji.map((item, index) => {
                    return (
                      <div
                        key={index}
                        onClick={() => {
                          sendMsg(item);
                          setShowEmoji(false);
                        }}
                      >
                        {item}
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
          <TextArea
            rows={6}
            value={text}
            onChange={(event) => setText(event.target.value)}
          />
          <div className="footer">
            <Button type="primary" onClick={() => sendMsg()}>
              发送
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ChatRoom;
